<?php
class FilePool extends CronjobCommandPool
{
	public $namespace;
	public $poolPath = null;
	protected $poolFile = null;
	public $fileMd5 = null;
	protected $_prototype;
	
	public function __construct(){
		$this->init();
	}
	
	public function init(){		
		$this->poolPath = Yii::getPathOfAlias('application.commands.pool.commands');
		$this->buildPool();
	}
		
	public function setNamespace($namesapce){
		$this->namespace = $namesapce;
		$this->poolFile = $this->poolPath.'/'.$this->namespace.'.cron';
		//$this->set(null);
	}
	
	public function setPrototype($prototype){
		$this->_prototype = $prototype;
	}
	
	public function getPrototype(){
		return $this->_prototype;
	}
	
	
	public function command($command){
		$this->set($command);
	}
	
	public function buildPool(){
		if (!file_exists($this->poolPath)) {
			mkdir($this->poolPath,0777,true);
		}		
	}
	
	public function set($command){
		file_put_contents($this->poolFile,$command);
		$this->fileMd5 = md5_file($this->poolFile);
	}
	
	public function get(){
		$command = file_get_contents($this->poolFile);
		$this->set(null);
		return $command;
	}
	
	public function clear(){
		unlink($this->poolFile);
	}
	
	public function runCommand(){
		if ($this->commandChange()) {
			$commandTemp = $this->get();
			$commandTempArray = explode(':',$commandTemp);
			$command = $commandTempArray[0];
			$command = trim($command);
			$commandMap = $this->getPrototype()->command();
			if (array_key_exists($command,$commandMap)) {
				unset($commandTempArray[0]);
				$commandParams = $commandTempArray;
				call_user_func_array(array($this->getPrototype(),$commandMap[$command]),$commandParams);
			}
		}
	}
	
	public function commandChange(){
		$fileMd5 = md5_file($this->poolFile);
		return $this->fileMd5 != $fileMd5;
	}
	
}

